﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using CoreEx.Services;
using LinFu.IoC.Configuration;
using LinFu.IoC.Interfaces;
using LinFu.IoC;
using LinFu.Reflection;

namespace CoreEx.Common.Implementation.Ioc
{
    [Implements(typeof(IDirectoryListing),ServiceName = "DefaultDirectoryLister")]
    public class DirectoryLister : IDirectoryListing, IInitialize
    {
        private IServiceContainer _serviceContainer;
        private IDictionary<string, IList<Type>> _assemblyWeavers;      

        public IEnumerable<string> GetFiles(string path, string searchPattern)
        {                        
            var files = Directory.GetFiles(path, searchPattern);
            var weaveTargetLoader = _serviceContainer.GetService<IWeaveTargetLoader>();
            
            weaveTargetLoader.Load(files);                       
            
            //Load all the files except the assemblies identified as a weave target.
            return files.Where(f => !_assemblyWeavers.ContainsKey(Path.GetFileName(f)));
        }

        public void Initialize(IServiceContainer source)
        {
            _serviceContainer = source;
            _assemblyWeavers = source.GetService<IDictionary<string, IList<Type>>>("AssemblyWeavers");            
        }
    }
}